package com.learn.springboot.service.order;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.util.ConverterUtils;
import com.learn.springboot.dao.dto.OrderDataExcelDto;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author suzheng
 * @date 2020-06-17
 **/
@Slf4j
public class ImportOrderExcelDataSheetListener extends AnalysisEventListener<OrderDataExcelDto> {

    @Getter
    private List<OrderDataExcelDto> orderDataExcelDtos = new ArrayList<>(10);

    @Setter
    @Getter
    private List<Object> heads;

    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        this.invokeHeadMap(ConverterUtils.convertToStringMap(headMap, context), context);
    }

    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        setHeads(headMap.values().stream().collect(Collectors.toList()));
    }

    @Override
    public void invoke(OrderDataExcelDto orderDataExcelDto, AnalysisContext analysisContext) {
        List<Object> dataList = analysisContext.readRowHolder().getCellMap().values().stream().map(cell -> {
            ReadCellData readCellData = ((ReadCellData) cell);
            if (readCellData.getType().equals(CellDataTypeEnum.STRING)) {
                return readCellData.getStringValue();
            } else if (readCellData.getType().equals(CellDataTypeEnum.NUMBER)) {
                return readCellData.getNumberValue();
            } else if (readCellData.getType().equals(CellDataTypeEnum.DATE)) {
                return readCellData.getDataFormatData().getFormat();
            } else if (readCellData.getType().equals(CellDataTypeEnum.BOOLEAN)) {
                return readCellData.getBooleanValue();
            } else {
                return readCellData.getData();
            }
        }).collect(Collectors.toList());
        orderDataExcelDto.setData(dataList);
        log.debug("{}", orderDataExcelDto);
        orderDataExcelDtos.add(orderDataExcelDto);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("所有数据解析完毕");
    }
}
